#include <iostream>
#include <string>
#include <deque>
#include <map>

using namespace std;

string start;
bool found;
int ntest;
map<string, bool> used;	// if not exists --> false; if exists and requested --> false
deque<string> q;
multimap<string, string> m;

void init()
{
	used.clear();
	used[start] = true;

	while (!q.empty()) q.pop_front();
	q.push_back(start);
}

void BFS()
{
	while (!q.empty())
	{
		string u = q.front();
		//cout << u << endl; //
		q.pop_front();

		for (map<string, string>::iterator i = m.begin(); i != m.end(); i++)
		{
			string s = i->first;

			//cout << "Doing " << i->first << " " << i->second << endl; //
			int l = s.size();
			int p = -1;
			while (true)
			{
				p = u.find(s, p+1);

				//cout << p << endl; //

				if ((p<0) || (p>=u.size())) break;

				//cout << u << endl; //
				//cout << u.substr(0, p) << endl; //
				//cout << u.substr(p+l, u.size()-(p+l)) << endl; //

				string v = u.substr(0, p) + i->second + u.substr(p+l, u.size()-(p+l));

				//cout << v << endl; //
				if (v.size() > 1500)
				{
					found = false;
					return;
				}

				if (!used[v])
				{
					used[v] = true;
					q.push_back(v);
					if (used.size() >= 1001)
					{
						found = false;
						return;
					}
				}
			}
		}
	}
}

int main()
{
	//freopen("10027.in", "r", stdin);

	scanf("%d\n", &ntest);
	scanf("\n");
	while (0 < ntest--)
	{
		found = true;

		getline(cin, start);
		start = start.substr(1, start.size()-2);

		//cout << start << endl;

		m.clear();
		while (true)
		{
			string s;
			if (!getline(cin, s)) break;
			if (s == "") break;

			//cout << s << endl;
			int p = s.find("->");

			m.insert( pair<string, string>(s.substr(1, p-2), s.substr(p+3, s.size()-(p+4))) );
			//cout << s.substr(1, p-2) << " " << s.substr(p+3, s.size()-(p+4)) << endl;
		}

		init();
		BFS();

		if (!found) cout << "Too many." << endl;
		else cout << used.size() << endl;
	}
	return 0;
}
